package com.gateway.core;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

import com.gateway.common.Common;
import com.gateway.entity.LogicServer;
import com.gateway.util.ParseXML;
import com.gateway.util.SigarTool;

/**
 * 网关服务器
 * 
 * @author Simple
 * @date 2013-6-28 上午11:25:37
 * @Description TODO
 */
public class Gateway {

  private Logger log=Logger.getLogger(this.getClass());

  private NioSocketAcceptor acceptor;

  // 逻辑服务器列表
  public static List<LogicServer> logicServerList=new ArrayList<LogicServer>();

  private void startGateway() {
    acceptor=new NioSocketAcceptor(Runtime.getRuntime().availableProcessors() + 1);
    DefaultIoFilterChainBuilder chain=acceptor.getFilterChain();
    // chain.addLast("LogFilter", new LoggingFilter());
    chain.addLast("GatewayProtocolFilter", new ProtocolCodecFilter(new GatewayProtocolCodecFactory(Charset.forName("utf-8"))));
    acceptor.setHandler(new GatewayHandler());
    acceptor.getSessionConfig().setReadBufferSize(1024 * 10);
    try {
      acceptor.bind(new InetSocketAddress(Common.PORT_GATEWAY));
      log.debug("GatewayServer started , PORT=" + Common.PORT_GATEWAY);
      pcInfo();
    } catch(IOException e) {
      e.printStackTrace();
    }
  }

  @SuppressWarnings("unused")
  private void initChildServerInfo() {
    log.debug("init logicServerInfo");
    ParseXML.readServerConfig(logicServerList);
    for(LogicServer info: logicServerList) {
      log.debug(info);
    }
  }

  public static void main(String[] args) {
    new Gateway().startGateway();
  }

  /**
   * 计算机信息
   */
  private void pcInfo() {
    Sigar sigar=new Sigar();
    try {
      SigarTool.outCpuInfo(sigar);
      // SigarTool.outCpuPerc(sigar);
      // SigarTool.outMemInfo(sigar);
      // SigarTool.outSwapInfo(sigar);
      // SigarTool.outNetInfo(sigar);
    } catch(SigarException e) {
      e.printStackTrace();
    }
  }
}
